package com.qingchi.server.controller;

import com.qingchi.base.constant.PlatformType;
import com.socialuni.social.model.common.ResultRO;
import com.qingchi.base.constant.ProviderType;
import com.qingchi.base.platform.weixin.login.LoginDataVO;
import com.qingchi.base.repository.user.AccountRepository;
import com.qingchi.base.service.LoginService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@RequestMapping("user")
public class PlatformLoginController {
    @Resource
    private LoginService loginService;
    @Resource
    private AccountRepository accountRepository;
    @Resource
    private RestTemplate restTemplate;

    //app端，小程序端，微信和qq登陆的接口，传入第三方返回的基础信息，昵称等，没有手机号，Provider = 'weixin' | 'qq'
    @PostMapping("platformLogin")
    public ResultRO<?> platformLogin(@RequestBody @Valid LoginDataVO loginVO) {
        //Provider = 'weixin' | 'qq'
        return getResultVO(loginVO);
    }

    //可以携带id也可以不携带，不携带返回时生成

    //app端，小程序端，微信和qq登陆的接口，传入第三方返回的基础信息，昵称等，没有手机号，Provider = 'weixin' | 'qq'
    @PostMapping("providerLogin")
    public ResultRO<?> providerLogin(@RequestBody @Valid LoginDataVO loginVO) {
        return getResultVO(loginVO);
    }

    private ResultRO<?> getResultVO(@RequestBody @Valid LoginDataVO loginVO) {
        //Provider = 'weixin' | 'qq'
        String provider = loginVO.getProvider();
        //手机登陆的时候为ProviderType.phone
        if (StringUtils.isEmpty(provider)) {
            provider = loginVO.getLoginType();
            loginVO.setProvider(provider);
        }
        String platform = loginVO.getPlatform();
        if (PlatformType.android.equals(platform)) {
            loginVO.setPlatform(PlatformType.app);
        }
        //todo 这接口有问题，应该拆开，手机号登陆不应该和三方登陆在一起
        if (ProviderType.phone.equals(provider)) {
            return loginService.phoneLogin(loginVO);
        } else {
            return loginService.providerLogin(loginVO);
        }
    }


}
